package com.cn.zy.zheda.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cn.zy.zheda.demo.constant.ParamConstant;
import com.cn.zy.zheda.demo.constant.UrlConstant;
import com.cn.zy.zheda.demo.controller.request.Alarm;
import com.cn.zy.zheda.demo.controller.request.UserReq;
import com.cn.zy.zheda.demo.controller.response.AlarmRes;
import com.cn.zy.zheda.demo.controller.response.LoginPass;
import com.cn.zy.zheda.demo.service.UrlService;
import com.cn.zy.zheda.demo.utils.HttpUtil;
import org.springframework.stereotype.Service;


/**
 * @author zhangyi
 * @date 2018/12/19 13:08
 */
@Service
public class UrlServiceImpl implements UrlService {

    /**
     * 登录成功返回
     *
     * @param user
     * @return
     */
    @Override
    public String login(UserReq user) {
        String token = null;
        try {
            String param = JSON.toJSONString(user);
            String result = HttpUtil.sendPostJson(UrlConstant.LOGIN_URL, param, null);
            Object o = JSON.parseObject(result, new TypeReference<LoginPass>() {});
            LoginPass loginPass = (LoginPass) o;
            token = loginPass.getToken();
        }catch (ClassCastException e){
            System.out.println("数据转换异常,这是是返回的json无法解析成用户实体");
        }catch (Exception e){
            System.out.println("远程登录异常,推测应该是用户名和密码错误,或者是token验证失效");
            System.out.println("详细错误信息:"+e.getMessage());
        }
        return token;
    }

    /**
     * 返回报警数据
     *
     * @param alarm
     * @param token
     * @return
     */
    @Override
    public String alarm(Alarm alarm,String token) {
        String alarmUrl = UrlConstant.ALARM_URL;
        //认证
        String authAlarm = alarmUrl.replace(ParamConstant.ALARM_1, alarm.getDeviceId())
                .replace(ParamConstant.ALARM_2, alarm.getLimit())
                .replace(ParamConstant.ALARM_3, alarm.getAscOrder());
        String res = HttpUtil.sendGet(authAlarm,token);
        //映射转换
        AlarmRes alarmRes = JSON.parseObject(res, AlarmRes.class);

        return alarmRes.toString();
    }
}
